package domain;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

import domain.exceptions.RestrictionBuyingException;


@Entity
@Table(name = "Subastas")
public class Auction extends PersistentEntity{
	public enum State{finalized, pending};
	
	@OneToOne
	private Item item;
	private double basePrice;
	private State state;
	@OneToMany
	@Cascade(value = {CascadeType.ALL, CascadeType.DELETE_ORPHAN})
	@JoinColumn(name="auction_id")
	private List<Offer> offers;
	
	//Hibernate
	public Auction(){
	}

	public Auction(Item item, double basePrice){
		this.offers=new ArrayList<Offer>();
		this.item=item;
		this.basePrice=basePrice;
		this.state=State.pending;
	}
	
	public void addOffer(Offer of) throws RestrictionBuyingException{
		if(state==State.finalized)
			throw new IllegalStateException();
		if(of.getOfferPrice()<basePrice)
			throw new IllegalStateException();
		if(item.canBuy(of.getUser()))
			this.offers.add(of);
		else
			throw new RestrictionBuyingException(RestrictionBuyingException.CANNOT_BUY_CODE);
	}
	
	public List<Offer> getOffers(){
		Collections.sort(this.offers);
		return this.offers;
	}
	
	public Offer getMaxOffer(){
		Offer aux=null;
		for(Offer of: offers){
			if(aux==null)
				aux=of;
			else if(of.offeredMore(aux))
				aux=of;
		}
		return aux;
	}
	
	public void deleteOffer(Offer offer){
		offers.remove(offer);
	}
	
	public Item getItem(){
		return this.item;
	}
	
	public double getBasePrice(){
		return this.basePrice;
	}
	
	public void finalizeAuction(){
		this.state=State.finalized;
	}
	
	public void restartAuction(){
		this.state=State.pending;
	}
	
	public State getState(){
		return this.state;
	}

}
